package org.gesplan.util;

import java.awt.Component;
import java.awt.Font;
import java.beans.Beans;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableCellRenderer;
import org.gesplan.ui.MainClass;

/**
 *
 * @author David
 */
public class Utils {

    private static final ResourceBundle bundle = ResourceBundle.getBundle("org/gesplan/properties/Bundle");
    private static Logger logger;
    private static EntityManagerFactory emf;
    private static EntityManager em;
    private static Properties iniProperties;
    private static boolean isLoaded = false;
    private static String connectionString;
    private static Connection connection;
    private static final String LOG_FOLDER = "log/";
    private static final String JASPERS_FOLDER = "jaspers/";
    private static final String REPORTS_FOLDER = "reports/";
    private static final String CONFIG_FILE = "config.properties";
    public static String jaspersFolder;
    public static String reportsFolder;


    static {
        
        try {
            if (!Beans.isDesignTime()) {
                jaspersFolder = new java.io.File(".").getCanonicalPath() + "/" + JASPERS_FOLDER;
                reportsFolder = new java.io.File(".").getCanonicalPath() + "/" + REPORTS_FOLDER;
                CalendarManager.initCalendar();
                Properties prop = getConfigFile();
                Map<String, String> properties = new HashMap<>();
                properties.put("javax.persistence.jdbc.url", prop.getProperty("URL", "jdbc:postgresql://servidor:5432/gesplan"));
                properties.put("javax.persistence.jdbc.driver", prop.getProperty("DRIVER", "org.postgresql.Driver"));
                properties.put("javax.persistence.jdbc.user", prop.getProperty("USER", "roses"));
                properties.put("javax.persistence.jdbc.password", prop.getProperty("PASSWORD", "pw_roses"));
                connectionString = prop.getProperty("URL", "jdbc:postgresql://servidor:5432/gesplan")
                    + "?user=" + prop.getProperty("USER", "roses")
                    + "&password=" + prop.getProperty("PASSWORD", "pw_roses");
                connection = DriverManager.getConnection(connectionString);
                emf = Persistence.createEntityManagerFactory(bundle.getString("DB_CONNECTION"), properties);
                em = emf.createEntityManager();
            }
        } catch (IOException | SQLException e) {
            logger.severe(e.getMessage());
            JOptionPane.showMessageDialog(null, e.getMessage(), "Error Entity Manager Factory", JOptionPane.ERROR_MESSAGE);
        }
        
    }


    public static Connection getConnection() {
        return connection;
    }


    public static boolean setConfigFile() {

        try {
            //configFolder = new java.io.File(".").getCanonicalPath() + "/" + CONFIG_FOLDER;                 
            String file = new java.io.File(".").getCanonicalPath() + "/" + CONFIG_FILE;
            File iniFile = new File(file);
            iniProperties = new Properties();
            iniProperties.load(new FileInputStream(iniFile));
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Error Config File", JOptionPane.WARNING_MESSAGE);
            return false;
        } catch (IOException e) {
            return false;
        }
        return true;

    }


    public static Properties getConfigFile() {
        if (iniProperties == null) {
            setConfigFile();
        }
        return iniProperties;
    }


    public static EntityManagerFactory getEntityManagerFactory() {
        return emf;
    }


    public static ResourceBundle getBundle() {
        return bundle;
    }


    public static Logger getLogger() {
        if (logger == null) {
            try {
                (new File(LOG_FOLDER)).mkdirs();
                String logFile = LOG_FOLDER + "log_" + getCurrentTimeStamp() + ".log";
                FileHandler fh = new FileHandler(logFile, true);
                LogFormatter lf = new LogFormatter();
                fh.setFormatter(lf);
                logger = Logger.getLogger(logFile);
                logger.addHandler(fh);
            } catch (IOException e) {
                JOptionPane.showMessageDialog(null, e.getMessage(), "Error al crear el fitxer de log", JOptionPane.ERROR_MESSAGE);
            }
        }
        return logger;

    }


    public static JProgressBar getProgressBar() {
        return MainClass.mdi != null ? MainClass.mdi.commonProgressBar : null;
    }


    public static JLabel getValidationLabel() {
        return MainClass.mdi != null ? MainClass.mdi.validationLabel : null;
    }


    public static JLabel getCurrentLabel() {
        return MainClass.mdi != null ? MainClass.mdi.currentLabel : null;
    }


    public static JLabel getTotalLabel() {
        return MainClass.mdi != null ? MainClass.mdi.totalLabel : null;
    }


    public static boolean isLoaded() {
        return isLoaded;
    }


    public static void setLoaded() {
        isLoaded = true;
    }


    public static void setRecordInfo(JTable masterTable) {
        if (MainClass.mdi != null) {
            Integer total = masterTable.getRowCount();
            MainClass.mdi.currentLabel.setText(bundle.getString("RECORD"));
            MainClass.mdi.totalLabel.setText(bundle.getString("OF") + total);
        }
    }


    public static void setRecordInfo(String current, String total) {
        if (MainClass.mdi != null) {
            MainClass.mdi.currentLabel.setText(bundle.getString("RECORD") + current);
            MainClass.mdi.totalLabel.setText(bundle.getString("OF") + total);
        }
    }


    public static String getCurrentTimeStamp() {
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyyMMdd");
        Date now = new Date();
        String date = sdfDate.format(now);
        return date;
    }


    public static String dateToString(Date date) {
        if (date == null){
            return "";
        }
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
        String parsedDate = sdfDate.format(date);
        return parsedDate;
    }


    public static int askQuestionYesNo(JPanel parent, String message, String title) {
        Object[] opcions = {bundle.getString("YES"), bundle.getString("NO")};
        int res = JOptionPane.showOptionDialog(parent, message, title,
            JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, opcions, opcions[0]);
        return res;
    }


    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void resetComponentsContainer(Object container) {
        
        Component[] components = null;
        if (container instanceof JPanel) {
            JPanel panel = (JPanel) container;
            components = panel.getComponents();
        } else if (container instanceof JScrollPane) {
            JScrollPane scrollPane = (JScrollPane) container;
            components = scrollPane.getComponents();
        }
        if (components == null) return;
        for (Component component : components) {
            if (component instanceof JTextField) {
                JTextField tf = (JTextField) component;
                tf.setText("");
            } else if (component instanceof JTextArea) {
                JTextArea ta = (JTextArea) component;
                ta.setText("");
            } else if (component instanceof JComboBox) {
                JComboBox cb = (JComboBox) component;
                cb.setSelectedIndex(-1);
            } else if (component instanceof JList) {
                JList lb = (JList) component;
                lb.setListData(new Object[0]);
            } else if (component instanceof JScrollPane) {
                JScrollPane sp = (JScrollPane) component;
                resetComponentsContainer(sp);
            }
        }
        
    }


    @SuppressWarnings("rawtypes")
	public static List execFunction(String function, Object[] params) {
        
        List list = null;
        try {
            Query qry = em.createNativeQuery(function);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    qry.setParameter(i + 1, params[i]);
                }
            }
            //Object obj = qry.getSingleResult();
            list = qry.getResultList();
        } catch (Exception e) {
            logger.severe(e.getMessage());
        }
        return list;
        
    }


    public static void copyFile(String srFile, String dtFile) {
        
        try {
            File f1 = new File(srFile);
            File f2 = new File(dtFile);
            InputStream in = new FileInputStream(f1);

            // Overwrite file.
            OutputStream out = new FileOutputStream(f2);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            logger.info("File copied");
        } catch (FileNotFoundException ex) {
            logger.warning(ex.getMessage() + " in the specified directory.");
        } catch (IOException ex) {
            logger.warning(ex.getMessage());
        }
        
    }
    
    
    public static void setTableHeader(JTable masterTable){
        Font font = new Font("Tahoma", Font.BOLD, 10);
        masterTable.getTableHeader().setFont(font);
        DefaultTableCellRenderer renderer = (DefaultTableCellRenderer) masterTable.getTableHeader().getDefaultRenderer();
        renderer.setHorizontalAlignment(JLabel.CENTER);      
    }
    
    
    public static String getMonthName(Integer month) {
        
        String monthString;        
        switch (month) {
            case 1:  monthString = "Gener";
                     break;
            case 2:  monthString = "Febrer";
                     break;
            case 3:  monthString = "Març";
                     break;
            case 4:  monthString = "Abril";
                     break;
            case 5:  monthString = "Maig";
                     break;
            case 6:  monthString = "Juny";
                     break;
            case 7:  monthString = "Juliol";
                     break;
            case 8:  monthString = "Agost";
                     break;
            case 9:  monthString = "Setembre";
                     break;
            case 10: monthString = "Octubre";
                     break;
            case 11: monthString = "Novembre";
                     break;
            case 12: monthString = "Desembre";
                     break;
            default: monthString = "Mes invàlid";
                     break;
        }
        return monthString;

    }    

}